package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("CrawlerfilecolumnService")
@Transactional

public class CrawlerfilecolumnServiceImpl extends CmiEmaService implements CrawlerfilecolumnService {
	public CrawlerfilecolumnServiceImpl() {
	}

	@Transactional
	public Crawlerfilecolumn saveCrawlerfilecolumn(Crawlerfilecolumn crawlerfilecolumn) {
		Set<Crawlerfilestandardcolumn> existingCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn = new HashSet<Crawlerfilestandardcolumn>();

		Set<Crawlerfilestandardcolumn> selectedCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn = crawlerfilecolumn
				.getCrawlerfilestandardcolumnsForCrawlerfilecolumn();

		if (crawlerfilecolumn.getId() == null) {

			Crawlerfilecolumn existingCrawlerfilecolumn = crawlerfilecolumnDAO
					.findCrawlerfilecolumnByPhysicalPrimaryKey(crawlerfilecolumn.getName());

			if (isEquals(crawlerfilecolumn, existingCrawlerfilecolumn)) {
				return existingCrawlerfilecolumn;
			}

			crawlerfilecolumn = crawlerfilecolumnDAO.store(crawlerfilecolumn);
			crawlerfilecolumnDAO.flush();

			for (Crawlerfilestandardcolumn relatedCrawlerfilestandardcolumn : selectedCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn) {
				relatedCrawlerfilestandardcolumn.getCrawlerfilecolumnsForCrawlerfilestandardcolumn()
						.add(crawlerfilecolumn);
				crawlerfilestandardcolumnDAO.store(relatedCrawlerfilestandardcolumn);
			}
		} else {
			Crawlerfilecolumn existingCrawlerfilecolumn = crawlerfilecolumnDAO
					.findCrawlerfilecolumnByPrimaryKey(crawlerfilecolumn.getId());

			existingCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn = existingCrawlerfilecolumn
					.getCrawlerfilestandardcolumnsForCrawlerfilecolumn();

			Set<Crawlerfilestandardcolumn> prepareDeleteCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn = new HashSet<Crawlerfilestandardcolumn>();
			Set<Crawlerfilestandardcolumn> prepareAddCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn = new HashSet<Crawlerfilestandardcolumn>();

			prepareDeleteCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn
					.addAll(selectedCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn);
			prepareDeleteCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn
					.addAll(existingCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn);

			prepareAddCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn
					.addAll(selectedCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn);
			prepareAddCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn
					.addAll(existingCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn);

			prepareDeleteCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn
					.removeAll(selectedCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn);
			prepareAddCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn
					.removeAll(existingCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn);

			for (Crawlerfilestandardcolumn relatedCrawlerfilestandardcolumn : prepareAddCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn) {

				relatedCrawlerfilestandardcolumn.getCrawlerfilecolumnsForCrawlerfilestandardcolumn()
						.add(existingCrawlerfilecolumn);
				crawlerfilestandardcolumnDAO.store(relatedCrawlerfilestandardcolumn);
			}

			for (Crawlerfilestandardcolumn relatedCrawlerfilestandardcolumn : prepareDeleteCrawlerfilestandardcolumnsForCrawlerfilestandardcolumn) {

				relatedCrawlerfilestandardcolumn.getCrawlerfilecolumnsForCrawlerfilestandardcolumn()
						.remove(existingCrawlerfilecolumn);
				crawlerfilestandardcolumnDAO.store(relatedCrawlerfilestandardcolumn);
			}
			crawlerfilecolumn = crawlerfilecolumnDAO.store(crawlerfilecolumn);
			crawlerfilecolumnDAO.flush();
		}

		crawlerfilestandardcolumnDAO.flush();
		return crawlerfilecolumn;
	}

	public void deleteCrawlerfilecolumn(Crawlerfilecolumn crawlerfilecolumn) {
		crawlerfilecolumnDAO.remove(crawlerfilecolumn);
		crawlerfilecolumnDAO.flush();
	}

	@Transactional
	public void deleteCrawlerfilecolumns(Set<Integer> deleteCrawlerfilecolumnsId) {
		Query query = crawlerfilecolumnDAO.createNamedQuery("deleteCrawlerfilecolumnsById", -1, -1);
		query.setParameter(1, deleteCrawlerfilecolumnsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Crawlerfilecolumn> loadCrawlerfilecolumns() {
		return crawlerfilecolumnDAO.findAllCrawlerfilecolumns();

	}

	@Transactional
	public Set<Crawlerfilecolumn> loadReferenceCrawlerfilecolumns(Set<Crawlerfilecolumn> crawlerfilecolumns) {
		Iterator<Crawlerfilecolumn> crawlerfilecolumnsIterator = crawlerfilecolumns.iterator();
		Set<Crawlerfilecolumn> referencedCrawlerfilecolumns = new HashSet<>();
		while (crawlerfilecolumnsIterator.hasNext()) {
			Crawlerfilecolumn currentCrawlerfilecolumn = crawlerfilecolumnsIterator.next();

			if (!currentCrawlerfilecolumn.getCrawlerfilestandardcolumnsForCrawlerfilecolumn().isEmpty()) {
				referencedCrawlerfilecolumns.add(currentCrawlerfilecolumn);
				continue;
			}
		}
		return referencedCrawlerfilecolumns;
	}

	public Set<Crawlerfilecolumn> loadCrawlerfilecolumnsByIdSet(Set<Integer> crawlerfilecolumnIdSet) {

		Iterator<Integer> crawlerfilecolumnIdIterator = crawlerfilecolumnIdSet.iterator();
		Set<Crawlerfilecolumn> crawlerfilecolumnSet = new HashSet<>();
		while (crawlerfilecolumnIdIterator.hasNext()) {
			Integer id = crawlerfilecolumnIdIterator.next();
			Crawlerfilecolumn currentCrawlerfilecolumn = crawlerfilecolumnDAO.findCrawlerfilecolumnById(id);
			crawlerfilecolumnSet.add(currentCrawlerfilecolumn);
		}
		return crawlerfilecolumnSet;
	}

	@Transactional
	public List<Crawlerfilecolumn> findAllCrawlerfilecolumns(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Crawlerfilecolumn>(
				crawlerfilecolumnDAO.findAllCrawlerfilecolumns(startResult, maxRows));
	}

	@Transactional
	public Crawlerfilecolumn findCrawlerfilecolumnByPrimaryKey(Integer id) {
		return crawlerfilecolumnDAO.findCrawlerfilecolumnByPrimaryKey(id);
	}

	@Transactional
	public Integer countCrawlerfilecolumns() {
		return ((Long) crawlerfilecolumnDAO.createQuerySingleResult("select count(o) from Crawlerfilecolumn o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countCrawlerfilecolumns(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Crawlerfilecolumn.class);
		return ((Long) crawlerfilecolumnDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countCrawlerfilecolumnsByName(String queryName) {
		Query query = crawlerfilecolumnDAO.createNamedQuery("countCrawlerfilecolumnsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countCrawlerfilecolumnsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Crawlerfilecolumn.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadCrawlerfilecolumnObjectReferencedSet(Crawlerfilecolumn crawlerfilecolumn) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> crawlerfilestandardcolumnsIds = new HashSet<Integer>();
		for (Crawlerfilestandardcolumn crawlerfilestandardcolumn : crawlerfilecolumn
				.getCrawlerfilestandardcolumnsForCrawlerfilecolumn()) {
			crawlerfilestandardcolumnsIds.add(crawlerfilestandardcolumn.getId());
		}
		objectReferencedSetMap.put("crawlerfilestandardcolumnsIds", crawlerfilestandardcolumnsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadCrawlerfilecolumnClassReferencedSet(Crawlerfilecolumn crawlerfilecolumn) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("crawlerfilestandardcolumns",
				crawlerfilestandardcolumnDAO.findAllCrawlerfilestandardcolumns());

		return classReferencedSetMap;
	}

	public boolean isEquals(Crawlerfilecolumn crawlerfilecolumn, Object obj) {
		if (obj == crawlerfilecolumn)
			return true;
		if (!(obj instanceof Crawlerfilecolumn))
			return false;
		Crawlerfilecolumn comparedCrawlerfilecolumn = (Crawlerfilecolumn) obj;
		if (!CheckPropertyEqual(crawlerfilecolumn.getName(), comparedCrawlerfilecolumn.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

